package fun.zhufn.oldcomm.model.service;

import fun.zhufn.oldcomm.model.bo.Path;
import fun.zhufn.oldcomm.model.bo.customlist.PathList;
import fun.zhufn.oldcomm.model.dao.GlobalDataDao;

import java.util.Objects;

public class PathManagerService {
    private static final PathManagerService INSTANCE = new PathManagerService();
    private PathManagerService(){}

    public static PathManagerService getInstance(){return INSTANCE;}
    private static final GlobalDataDao dataDao = GlobalDataDao.getInstance();

    /**
     * @return 线路列表
     */
    public PathList getPathList() {
        var ret = new PathList();
        ret.fromJsonList(dataDao.getPathJsonList());
        return ret;
    }

    /**
     * @param ol 线路列表
     * @throws Exception 文件错误
     */
    public void setPathList(PathList ol) throws Exception {
        if (ol == null) return;
        dataDao.updatePathJsonList(ol.toJsonList());
        dataDao.saveToFile();
    }

    /**
     * @param o 线路
     * @throws Exception 文件错误
     */
    public void addPath(Path o) throws Exception {
        if (o == null) return;
        for (var p: getPathList().getData()) {
            if (p.getCode().equals(o.getCode())) {
                throw new Exception();
            }
        }
        var ol = getPathList();
        var lo = ol.getData();
        lo.add(o);
        ol.setData(lo);
        setPathList(ol);
    }

    /**
     * @param o 线路
     * @throws Exception 文件错误
     */
    public void editPath(Path o) throws Exception {
        if (o == null) return;
        removePath(o.getCode());
        var ol = getPathList();
        var lo = ol.getData();
        lo.add(o);
        ol.setData(lo);
        setPathList(ol);
    }

    /**
     * @param x 线路代码
     * @return 是否成功
     * @throws Exception 文件错误
     */
    public boolean removePath(String x) throws Exception {
        var ol = getPathList();
        var lo = ol.getData();
        for (int i = 0; i < lo.size(); ++i) {
            if (Objects.equals(lo.get(i).getCode(), x)) {
                lo.remove(i);
                ol.setData(lo);
                setPathList(ol);
                return true;
            }
        }
        return false;
    }

    public void setPathEnd(String code, int endTime) throws Exception {
        var ol = getPathList();
        var lo = ol.getData();
        for (int i = 0; i < lo.size(); ++i) {
            if (Objects.equals(lo.get(i).getCode(), code)) {
                var t = lo.get(i);
                t.setEndTime(endTime);
                lo.set(i, t);
                ol.setData(lo);
                setPathList(ol);
                dataDao.saveToFile();
                return;
            }
        }
    }
}
